const e = `<!--
 * @Author: Quarter
 * @Date: 2023-10-09 15:05:06
 * @LastEditors: Quarter
 * @LastEditTime: 2024-12-27 10:14:16
 * @FilePath: /simple-ui/packages/documents/src/views/desktop/image-preview/default-image-preview.vue
 * @Description: 默认 Image 组件示例
-->
<template>
  <s-flex gap="1em">
    <s-button theme="primary" @click="handleSyncPreview">预览图片</s-button>
    <s-button theme="primary" @click="handleAsyncPreview">异步预览</s-button>
    <s-image-preview ref="preview1" :src="url"></s-image-preview>
    <s-image-preview
      ref="preview2"
      :src="url"
      blob
      :blob-handler="handleBlobHandler"
    ></s-image-preview>
  </s-flex>
</template>

<script lang="ts">
import { type ImagePreviewInstance } from "@smartcity/simple-ui";
import DemoImage from "documents/assets/demo.jpg";
import { Component, Vue } from "vue-property-decorator";

@Component
export default class DefaultImagePreview extends Vue {
  $refs!: {
    preview1?: ImagePreviewInstance; // 预览组件
    preview2?: ImagePreviewInstance; // 预览组件
  };

  /**
   * @description: 图片路径
   * @private
   * @readonly
   * @type {string}
   */
  readonly url = DemoImage;

  /**
   * @description: 处理预览静态图片
   * @private
   * @returns
   */
  handleSyncPreview(): void {
    const { preview1 } = this.$refs;
    preview1?.open();
  }

  /**
   * @description: 处理按钮点击
   * @private
   * @returns
   */
  handleAsyncPreview(): void {
    const { preview2 } = this.$refs;
    preview2?.open();
  }

  /**
   * @description: 处理生成 Blob 文件，模拟真实场景的 http 请求等异步操作
   * @private
   * @param {string} src 文件参数
   * @returns {Promise<Blob>}
   */
  handleBlobHandler(src: string): Promise<Blob> {
    return new Promise<Blob>((resolve, reject) => {
      setTimeout(() => {
        if (typeof src !== "string") {
          reject();
          return;
        }
        const image = new Image();
        image.addEventListener("load", ({ target }) => {
          if (target instanceof Image) {
            const canvas = document.createElement("canvas");
            const ctx = canvas.getContext("2d");
            canvas.width = image.width;
            canvas.height = image.height;
            ctx?.drawImage(image, 0, 0);
            const [, body] = canvas.toDataURL("image/png", 1).split(",");
            const bstr = atob(body);
            let n = bstr.length;
            const u8arr = new Uint8Array(n);
            while (n--) {
              u8arr[n] = bstr.charCodeAt(n);
            }
            resolve(new Blob([u8arr], { type: "image/png" }));
          }
        });
        image.addEventListener("error", () => {
          reject();
        });
        image.src = src;
      }, 3000);
    });
  }
}
<\/script>
`; export { e as default };
